package com.yishan.controller;

import com.github.pagehelper.PageInfo;
import com.yishan.domain.Company;
import com.yishan.service.CompanyService;
import com.yishan.utils.BeanUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author yishan
 * @Date 2021/4/12 0012 20:53
 * @Version 1.0
 */

@Controller
@RequestMapping("/company")
public class CompanyController {

	@Autowired
	private CompanyService companyService;


	/**
	 * 查询所有
	 *
	 * @param model
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/list")
	private String list(Model model, HttpServletRequest request)
			throws ServletException, IOException {

		int page = 1;
		int size = 5;

		if (StringUtils.isNotBlank(request.getParameter("page"))) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (StringUtils.isNotBlank(request.getParameter("size"))) {
			size = Integer.parseInt(request.getParameter("size"));
		}

		PageInfo info = companyService.findAll(page, size);

		model.addAttribute("page", info);
		return "/WEB-INF/pages/company/list.jsp";

	}

	/**
	 * 跳转到添加页面
	 *
	 * @return
	 */
	@RequestMapping("/toAdd")
	private String toAdd() {

		return "/WEB-INF/pages/company/add.jsp";

	}

	/**
	 * 添加操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/save")
	private String save(HttpServletRequest request) {

		Company company = BeanUtil.fillBean(request, Company.class);
		companyService.save(company);

		return "redirect:" + request.getContextPath() + "/company/list";

	}

	/**
	 * 跳转到修改页面
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toEdit")
	private String toEdit(String id, Model model) {

		Company company = companyService.findById(id);

		model.addAttribute("company", company);

		return "/WEB-INF/pages/company/update.jsp";


	}

	/**
	 * 修改操作
	 *
	 * @param company
	 * @return
	 */
	@RequestMapping("/edit")
	private String edit(Company company) {

		companyService.update(company);

		return "redirect:/company/list";

	}

	/**
	 * 删除操作
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	private String delete(String ids) {

		companyService.deleteMany(ids);

		return "redirect:/company/list";

	}
}
